import sys, getopt, random, requests, importlib, os, re


def main(args):
    try:
        options, args = getopt.getopt(args, "hp:r", ['help', 'path=', 'rule=', ''])
    except getopt.GetoptError:
        sys.exit(1)
    base_path = os.path.abspath('./')
    path = ''
    rule = ''

    for option, value in options:
        if option in ('-h','--help'):
            print('python ebook.py --rule=分页正则 --path=文件路径')
            sys.exit(0)
        if option in ('-p', '--path'):
            path = os.path.join(base_path,value)
            base_path = os.path.join(os.path.dirname(path),'contents')
            if not os.path.exists(path):
                print(path + ' 文件不存在')
                sys.exit(1)

            if not os.path.exists(base_path):
                os.mkdir(base_path)
            else:
                print('目录已存在')

        if option in ('-r', '--rule'):
            rule = re.compile(value)

    with open(path, 'r') as file:
        index = 1
        dst_path = os.path.join(base_path, 'content_' + str(index) + '.html')
        dst_file = open(dst_path, 'w', encoding='utf-8')
        i = 0
        for line in file:
            i = i + 1
            if i == 1:
                dst_file.write('<h1>' + line + '</h1>')
                continue
            match = rule.match(line)
            if match is not None:
                dst_file.close()
                index = index + 1
                dst_path = os.path.join(base_path, 'content_' + str(index) + '.html')
                dst_file = open(dst_path,'w', encoding='utf-8')
                dst_file.write('<h1>' + line + '</h1>')
                print('正在处理：' + line)
            else:
                dst_file.write('<p>' + line + '</p>')

    print('处理完成')


if __name__ == '__main__':
    main(sys.argv[1:])
